﻿namespace EyeOpen.TestHelpers
{
    using System;
    using System.IO;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    public static class TestExtension
    {
        public static void InitializeAssembly(TestContext testContext)
        {
            var solutionFolderName =
                testContext.TestDeploymentDir
                .Substring(0, testContext.TestDeploymentDir.IndexOf(@"\testresults", StringComparison.InvariantCultureIgnoreCase));

            var librariesFolderName = Path.Combine(solutionFolderName, "Lib");
            CopyFromLibrariesToTestTargetDirectory(testContext, librariesFolderName);

            var outFolderName = Path.Combine(solutionFolderName, "Out");
            CopyFromLibrariesToTestTargetDirectory(testContext, outFolderName);

            foreach (var file in new DirectoryInfo(solutionFolderName).GetFiles("*.Unity.config", SearchOption.AllDirectories))
            {
                try
                {
                    var destinationFile = Path.Combine(testContext.TestDeploymentDir, file.Name);
                    file.CopyTo(destinationFile, true);
                }
                catch (UnauthorizedAccessException)
                {
                }
            }
        }

        private static void CopyFromLibrariesToTestTargetDirectory(TestContext testContext, string folderName)
        {
            var librariesFolder = new DirectoryInfo(folderName);

            if (!librariesFolder.Exists)
            {
                return;
            }

            foreach (var file in librariesFolder.GetFiles("*.*", SearchOption.AllDirectories))
            {
                var destinationFile = new FileInfo(Path.Combine(testContext.TestDeploymentDir, file.Name));

                try
                {   
                    destinationFile.Delete();
                    file.CopyTo(destinationFile.FullName, true);
                }
                catch (UnauthorizedAccessException)
                {
                }
            }
        }
    }
}